package com.enjoylearning.content.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.enjoylearning.base.exception.XueChengPlusException;
import com.enjoylearning.content.mapper.TeachplanMapper;
import com.enjoylearning.content.mapper.TeachplanMediaMapper;
import com.enjoylearning.content.model.dto.BindTeachplanMediaDto;
import com.enjoylearning.content.model.dto.SaveTeachplanDto;
import com.enjoylearning.content.model.dto.TeachplanDto;
import com.enjoylearning.content.model.po.Teachplan;
import com.enjoylearning.content.model.po.TeachplanMedia;
import com.enjoylearning.content.service.TeachPlanService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TeachPlanServiceImpl implements TeachPlanService {

    @Autowired
    TeachplanMapper teachplanMapper;
    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;

    @Override
    public List<TeachplanDto> selectTeachplanById(Long id) {
        List<TeachplanDto> teachplanDtos = teachplanMapper.selectTeachPlanById(id);
        return teachplanDtos;
    }

    @Override
    public void saveTeachplan(SaveTeachplanDto teachplanDto) {
        if (teachplanDto.getPname() == null || teachplanDto.getPname().isEmpty() || teachplanDto.getPname().isBlank()) {
            XueChengPlusException.cast("名称不能为空");
        }
        Teachplan teachplan = new Teachplan();
        BeanUtils.copyProperties(teachplanDto, teachplan);
        //判断是新增或修改
        if (teachplanDto.getId() == null) {
            //新增
            //确定排序字段
            if (teachplanDto.getParentid() != null) {
                Integer count = teachplanMapper.selectCount(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getParentid, teachplanDto.getParentid())
                        .eq(Teachplan::getCourseId, teachplanDto.getCourseId()));
                teachplan.setOrderby(count + 1);
            }
            teachplanMapper.insert(teachplan);
        }else {
            //修改
            teachplanMapper.updateById(teachplan);
        }
    }

    @Transactional
    @Override
    public void deleteTeachplan(Long id) {
        //非空以及权限校验‘
        if (id == null) {
            throw new RuntimeException("ID is null");
        }
        //判断是否为本机构的课程
        //判断删除的课程计划类型
        Teachplan teachplan = teachplanMapper.selectOne(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getId, id));
        if (teachplan == null) {
            throw new RuntimeException("teachplan is null");
        }
        //删除的是一级目录
        if (teachplan.getParentid() == 0){
            if (!teachplanMapper.selectList(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getParentid, teachplan.getId())).isEmpty()) {
                XueChengPlusException.cast("课程计划还有子级信息，无法操作");
            }
            teachplanMapper.deleteById(id);
            //一级目录排序字段重排
            teachplanMapper.redoOrderBy(teachplan.getCourseId(),teachplan.getParentid(),teachplan.getOrderby());
        }else {
            //删除的是二级目录
            //删除teachplan表
            teachplanMapper.deleteById(id);
            //删除teachmedia表
            teachplanMediaMapper.deleteById(id);
            //二级目录排序字段重排
            teachplanMapper.redoOrderBy(teachplan.getCourseId(),teachplan.getParentid(),teachplan.getOrderby());
        }
    }

    @Override
    public void moveDownTeachplan(Long id) {
        Teachplan teachplan = teachplanMapper.selectOne(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getId, id));
        Integer orderBy = teachplan.getOrderby();
        //判断该节点下是否还有节点
        List<Teachplan> teachplans = teachplanMapper.selectList(new LambdaQueryWrapper<Teachplan>().gt(Teachplan::getOrderby, orderBy)
                .eq(Teachplan::getCourseId, teachplan.getCourseId()).eq(Teachplan::getParentid, teachplan.getParentid()));
        if (teachplans == null || teachplans.isEmpty()) {
            XueChengPlusException.cast("已经到底啦");
        }
        Teachplan uped = teachplanMapper.selectOne(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getOrderby, orderBy + 1)
                .eq(Teachplan::getCourseId, teachplan.getCourseId()).eq(Teachplan::getParentid, teachplan.getParentid()));
        teachplanMapper.moveDown(id,orderBy);
        teachplanMapper.moveUP(uped.getId(),orderBy+1);
    }

    @Override
    public void moveupTeachplan(Long id) {
        Teachplan teachplan = teachplanMapper.selectOne(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getId, id));
        Integer orderBy = teachplan.getOrderby();
        //判断该节点下是否还有节点
        List<Teachplan> teachplans = teachplanMapper.selectList(new LambdaQueryWrapper<Teachplan>().lt(Teachplan::getOrderby, orderBy)
                .eq(Teachplan::getCourseId, teachplan.getCourseId()).eq(Teachplan::getParentid, teachplan.getParentid()));
        if (teachplans == null || teachplans.isEmpty()) {
            XueChengPlusException.cast("你要上天吗");
        }
        Teachplan downed = teachplanMapper.selectOne(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getOrderby, orderBy -1)
                .eq(Teachplan::getCourseId, teachplan.getCourseId()).eq(Teachplan::getParentid, teachplan.getParentid()));
        teachplanMapper.moveUP(id,orderBy);
        teachplanMapper.moveDown(downed.getId(),orderBy-1);
    }

    @Override
    public void associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        //先删除原有记录
        int delete = teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId, bindTeachplanMediaDto.getTeachplanId()));
        if (delete <= 0) {
            XueChengPlusException.cast("删除失败");
        }
        //获取courseId
        Teachplan teachplan = teachplanMapper.selectOne(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getId, bindTeachplanMediaDto.getTeachplanId()));
        if (teachplan == null) {
            XueChengPlusException.cast("课程计划不存在");
        }
        Long courseId = teachplan.getCourseId();
        //再添加记录
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        BeanUtils.copyProperties(bindTeachplanMediaDto, teachplanMedia);
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setCourseId(courseId);
        teachplanMediaMapper.insert(teachplanMedia);
    }

    @Override
    public void deleteAssociationMedia(String teachPlanId, String mediaId) {
        //据说前端传来的是字符串☺☝
        Long m = Long.parseLong(mediaId);
        Long t = Long.parseLong(teachPlanId);
        //可能不同的课程计划绑定同一个媒资，所以条件为课程计划ID+媒资Id
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getMediaId,m)
                .eq(TeachplanMedia::getTeachplanId,t));
    }
}
